package com.bbs.system;

import com.bbs.model.UserParams;
import com.bbs.user.UserInfo;
import com.bbs.user.UserService_v2;
import com.bbs.utils.Common;
import com.bbs.utils.SystemEnum;
import com.bbs.utils.SystemResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/system")
public class SystemApiController {

    @Autowired
    UserService_v2 userService_v2;

    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public SystemResult loginIn(HttpServletRequest request, UserParams userParams) {

        if (StringUtils.isBlank(userParams.getUsername())) {
            return new SystemResult(SystemEnum.RESULT_ERROR.getCode(),"用户名不能为空");
        }
        if (StringUtils.isNotBlank(userParams.getPassword())){
            userParams.setPassword(Common.EncoderByMd5(userParams.getPassword()));
        } else {
            return new SystemResult(SystemEnum.RESULT_ERROR.getCode(),"密码不能为空");
        }
        UserInfo userInfo = userService_v2.login(userParams);
        if (userInfo != null){
            request.getSession().setAttribute("user",userInfo);
            return new SystemResult(SystemEnum.RESULT_OK.getCode(),"登陆成功");
        } else {
            return new SystemResult(SystemEnum.RESULT_ERROR.getCode(),"登陆失败!用户名或密码错误");
        }

    }

    @RequestMapping(value = "/logout")
    public SystemResult logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return new SystemResult(SystemEnum.RESULT_OK.getCode(),"注销成功");
    }
}
